<template>
  <div class="add_good">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home/welcome">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="curindex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="curindex"
          :before-leave="tabChange"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名" size="normal" prop="goods_name">
              <el-input v-model="addForm.goods_name" placeholder size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品价格" size="normal" prop="goods_price">
              <el-input v-model="addForm.goods_price" size="normal" type="number" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品数量" size="normal" prop="goods_number">
              <el-input v-model="addForm.goods_number" size="normal" type="number" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品重量" size="normal" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number" size="normal" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品分类" size="normal" prop="goods_cat">
              <el-cascader
                size="medium"
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children'}"
                @change="cateChange"
                clearable
                filterable
                ref="parentCateList"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              size="normal"
              v-for="(item) in paramsList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(item2,index) in item.attr_vals"
                  :key="index"
                  :label="item2"
                >{{item2}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              size="normal"
              v-for="item in staticList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals" size="normal" clearable></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="headerObj"
              :on-remove="removeimg"
              :on-preview="preview"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              size="default"
              @click="addGood"
              class="addbutton"
            >{{id==0?'添加商品':'修改商品'}}</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 预览图片的对话框 -->
      <el-dialog title="图片预览" :visible.sync="picFlag" width="50%">
        <div class="preview">
          <img :src="imgsrc" />
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'addGood',
  props: ['id'],
  data () {
    return {
      curindex: '0',
      // 添加的商品信息
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      //分类列表信息 
      cateList: [],
      // 选择的分类
      selectCate: "",
      // 动态参数和信息
      paramsList: [],
      // 静态属性的值
      staticList: [],
      // 上传图片中的头部信息
      headerObj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 预览图片对话框呈现
      picFlag: false,
      // 预览图片的src
      imgsrc: "",
      // 当前上传文件的列表
      fileList: [],
      // 添加商品的规则
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ]
      }
    }
  },
  methods: {
    // 请求所有分类列表信息
    async getCategories () {
      const res = await this.axios.get("categories")
      if (res.meta.status != 200)
        return this.$message.error({
          message: "获取商品分类失败",
          duration: 1000
        })
      this.cateList = res.data;
    },
    cateChange () {
      if (this.addForm.goods_cat.length != 3) {
        this.addForm.goods_cat = []
        return false;
      }
    },
    // 标签切换之前做预验证，验证通过才能切换
    tabChange (activeName, oldactiveName) {
      let flag = true;
      if (oldactiveName == '0') {
        // 如果是从第一个开始的验证本页面的信息
        this.$refs.addForm.validate(valid => {
          if (valid && this.addForm.goods_cat.length == 3) { }
          else {
            this.$message.error({
              message: "请先完成基本信息的填写",
              duration: 1000
            })
            flag = false;
          }
        })
      }
      return flag;
    },
    // 点击tabs进行切换时
    tabClick (activeName) {
      // 如果是跳到第二个动态参数面板
      if (this.curindex == 1) {
        this.getCategoriesParams("many")
      }
      if (this.curindex == 2) {
        this.getCategoriesParams("only")
      }
    },
    // 获取动态参数和属性的方法
    async getCategoriesParams (sel) {
      const res = await this.axios.get('categories/' + this.cId + '/attributes', { params: { sel } });
      console.log(res.data);
      if (sel == "many") {
        res.data.forEach(element => {
          element.attr_vals = element.attr_vals.length == 0 ? [] : element.attr_vals.split(' ');
        });
        this.paramsList = res.data;
      }
      else
        this.staticList = res.data;
    },
    // 在文件上传成功后进行路径的保存
    handleSuccess (res) {
      console.log(res);
      console.log(res.data.tmp_path);
      this.addForm.pics.push({ pic: res.data.tmp_path });

      console.log('3123');

    },
    // 移除图片时的操作
    removeimg (file) {
      if (this.id == 0) {
        const temp_path = file.response.data.tmp_path;
        this.addForm.pics = this.addForm.pics.filter(item => {
          if (item.pics_big_url == temp_path)
            return false;
          else
            return true;
        })
      }
      else {
        console.log(file.url.split('goodspics/')[1]);
        const path = file.url;
        this.addForm.pics = this.addForm.pics.filter(item => {
          if (item.pics_big.split("big_")[1] == path.split('goodspics/')[1])
            return false;
          else
            return true;
        })
      }

      console.log(this.addForm.pics);

    },
    // 点击图片进行预览
    preview (file) {
      if (this.id == 0) {
        this.imgsrc = file.response.data.url;
      }
      else
        this.imgsrc = file.url;
      this.picFlag = true;
    },
    // 添加商品或者修改商品
    async addGood () {
      //  在发起请求之前对分类数据进行处理  符合接口格式
      if (typeof this.addForm.goods_cat != 'string')
        this.addForm.goods_cat = this.addForm.goods_cat.join(",");
      //  在发起请求之前对商品的静态属性和动态参数数据进行处理 
      this.addForm.attrs = [];
      this.paramsList.forEach(item => {
        this.addForm.attrs.push({ attr_id: item.attr_id, attr_val: item.attr_vals.join(' ') })
      })
      this.staticList.forEach(item => {
        this.addForm.attrs.push({ attr_id: item.attr_id, attr_val: item.attr_vals })
      })
      console.log(this.addForm);
      let res;
      if (this.id == 0) {
        res = await this.axios.post('goods', this.addForm);
      }
      else {
        this.addForm.pics = this.addForm.pics.map(item => {
          let obj = {};
          if (!item.pic) {
            obj.pic = 'tmp_uploads' + '\\' + item.pics_big.split("big_")[1];
            return obj;
          }
          return item;
        })
        console.log(this.addForm);
        console.log('---');
        res = await this.axios.put('goods/' + this.id, this.addForm);
      }
      if (res.meta.status != 201 && res.meta.status != 200)
        return this.$message.error({
          message: this.id == 0 ? "添加商品失败" : "修改商品失败",
          duration: 1000
        })
      this.$message.success({
        message: this.id == 0 ? "添加商品成功" : '修改商品成功',
        duration: 1000
      })
      // 转回列表页
      this.$router.push("/home/goods");
    },
    // 获取当前id的数据
    async getGoods () {
      if (this.id != 0) {
        const res = await this.axios.get("goods/" + this.id);
        res.data.goods_cat = res.data.goods_cat.split(",").map(item => parseInt(item));
        this.addForm.goods_name = res.data.goods_name;
        this.addForm.goods_price = res.data.goods_price;
        this.addForm.goods_number = res.data.goods_number;
        this.addForm.goods_weight = res.data.goods_weight;
        this.addForm.goods_introduce = res.data.goods_introduce;
        this.addForm.attrs = this.addForm.attrs.concat(res.data.attrs);
        this.addForm.goods_cat = res.data.goods_cat;
        console.log(res.data);
        if (res.data.pics.length == 0) return
        res.data.pics.forEach(item => {
          this.fileList.push({ name: "1.png", url: item.pics_big_url.split("big_").join('') })
        })
      }
    }
  },
  created () {
    this.getGoods();
    this.getCategories();
  },
  computed: {
    // 最后分类的id
    cId () {
      return this.addForm.goods_cat[2]
    }
  }
}
</script>

<style lang="scss" >
.add_good {
  text-align: left;
  .el-steps {
    margin: 15px 0;
  }
  .el-step__title {
    font-size: 14px;
  }
  .el-form-item__label {
    padding-bottom: 0 !important;
  }
  .el-upload__tip {
    margin-top: 10px;
    line-height: normal;
  }
  .preview {
    width: 50%;
    margin: 0 auto;
    img {
      width: 100%;
    }
  }
  .ql-editor {
    min-height: 300px;
  }
  .addbutton {
    margin-top: 20px;
    float: right;
  }
}
</style>